package com.sjs.boot.dynamic.core.run.response;

import com.sjs.boot.dynamic.core.run.MethodContext;
import com.sjs.boot.dynamic.facade.run.AbstractResponser;
import com.sjs.boot.dynamic.protocol.Const;
import com.sjs.boot.dynamic.util.JsonUtil;

import javax.servlet.ServletException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

/**
 * @author uto_dev_008
 * @desc
 * @since 2021/11/30 14:02
 * Copyright (c) 2021 南京友拓信息技术有限公司 All rights reserved
 */
public class JsonResponser extends AbstractResponser {
    @Override
    public boolean init() {
        return true;
    }

    @Override
    public void destroy() {

    }

    @Override
    protected void output(MethodContext context, OutputStream out, Map<String, Object> model) throws ServletException, IOException {
        String resp = context.getResult();
        byte[] bytes;

        if (resp == null) {
            bytes = JsonUtil.mapToBytes(model);
        } else {
            bytes = resp.getBytes(Const.DEFAULT_CHARSET);
        }
        //只有json格式的才需要加密，html无需加密
        output(context, out, bytes);
    }

    @Override
    protected String getContentType(MethodContext context) {
        return Const.JSON_CONTENT_TYPE;
    }
}
